var app = getApp();
var baseUrl = app.url;

function bestCurl(method = 'GET',url,func,data = {},path = '../') {
    let SESSID = wx.getStorageSync('PHPSESSID');
    if(SESSID){
        var PHPSESSID = '?PHPSESSID='+SESSID;
    }else{
        PHPSESSID = '?';
    }
    new Promise((resolve, reject) => {
        wx.request({
          url: baseUrl + url + PHPSESSID,
          data: data,
          method:method,
          header: { 'Content-Type': 'application/json' },
          success: resolve,
          fail: reject
        })
    })
    .then(res=>{
        if(res.data.code==0){
            bestLogin()
            .then(res=>{
                //登录发生成功后返回
                if(res.data.code==1){
                    wx.setStorageSync("PHPSESSID",res.data.data.PHPSESSID);
                    wx.setStorageSync("nodes",res.data.data.nodes);
                    // 递归
                    bestCurl(method,url,func,data);
                }else if(res.data.code==10001){
                    wx.showModal({
                        content: '当前用户未绑定，请使用账号密码登录',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                wx.reLaunch({
                                    url: path+'login/login',
                                });
                            }
                        }
                    });
                }
            })
            .catch(e=>{
                console.log(e);
            })
        }else{
            func(res);
            
        }

    })
    .catch(e=>{
        console.log(e);
    })
}

function bestLogin() {
    return new Promise((resolve, reject) => {
        wx.login({
            success: function(res) {
                if (res.code) {
                    wx.request({
                        url: baseUrl + '/login/login',
                        method:'POST',
                        data: {
                            code: res.code
                        },
                        success: resolve,
                        fail:reject
                    })
                } else {
                  console.log('获取用户登录态失败！' + res.errMsg)
                }
            },
            fail:function () {
                console.log('登录接口调用失败')
            }
        });
    })
}

module.exports = {
bestCurl: bestCurl   
}
